<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="24">
          <a-form-item label="隐患名称" v-bind="validateInfos.dangerName">
	          <a-textarea v-model:value="formData.dangerName" :rows="4" placeholder="请输入隐患名称" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="隐患描述" v-bind="validateInfos.dangerDesc">
	          <a-textarea v-model:value="formData.dangerDesc" :rows="4" placeholder="请输入隐患描述" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="隐患产生原因" v-bind="validateInfos.dangerReason">
	          <a-textarea v-model:value="formData.dangerReason" :rows="4" placeholder="请输入隐患产生原因" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="隐患等级" v-bind="validateInfos.dangerLevel">
	          <j-dict-select-tag type='radio' v-model:value="formData.dangerLevel" dictCode="dangerLevel" placeholder="请选择隐患等级" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="隐患来源" v-bind="validateInfos.dangerSrc">
	          <j-dict-select-tag v-model:value="formData.dangerSrc" dictCode="dangerSrc" placeholder="请选择隐患来源" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="隐患治理类型" v-bind="validateInfos.dangerManageType">
	          <j-dict-select-tag type='radio' v-model:value="formData.dangerManageType" dictCode="dangerManageType" placeholder="请选择隐患治理类型" :disabled="disabled" @change="changeDangerManageType"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属装置" v-bind="validateInfos.riskDeviceId">
            <j-dict-select-tag v-model:value="formData.riskDeviceId" dictCode="tb_base_risk_device,name,id" placeholder="请选择所属装置" :disabled="disabled" @change="changeDeviceId"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属单元" v-bind="validateInfos.riskUnitId">
	          <j-dict-select-tag v-model:value="formData.riskUnitId" :dictCode="argument.unitDictCode" placeholder="请选择所属单元" :disabled="argument.riskUnitFlag"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="资金" v-bind="validateInfos.cost">
	          <a-input-number v-model:value="formData.cost" placeholder="请输入资金" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.dangerManageType == '1'">
          <a-form-item label="隐患治理期限" v-bind="validateInfos.dangerManageDeadline">
		        <a-date-picker placeholder="请选择隐患治理期限"  v-model:value="formData.dangerManageDeadline" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="隐患状态" v-bind="validateInfos.dangerState">
	          <j-dict-select-tag v-model:value="formData.dangerState" dictCode="dangerState" placeholder="请选择隐患状态" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="隐患类型" v-bind="validateInfos.hazardDangerType">
	          <j-dict-select-tag v-model:value="formData.hazardDangerType" dictCode="hazardDangerType" placeholder="请选择隐患类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="登记人姓名" v-bind="validateInfos.registrant">
			      <j-select-user v-model:value="formData.registrant" disabled="true"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="控制措施" v-bind="validateInfos.controlMeasures">
            <a-textarea v-model:value="formData.controlMeasures" :rows="4" placeholder="请输入控制措施" :disabled="disabled"/>
            <!-- <a-input v-model:value="formData.controlMeasures" placeholder="请输入控制措施" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="管控措施" v-bind="validateInfos.riskMeasureId">
	          <j-search-select v-model:value="formData.riskMeasureId" dict="tb_base_control_measures,risk_measure_desc,id" :disabled="disabled" />
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="12">
          <a-form-item label="登记时间" v-bind="validateInfos.registTime">
		        <a-date-picker placeholder="请选择登记时间"  v-model:value="formData.registTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled="true"/>
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="整改人" v-bind="validateInfos.liablePerson">
			      <j-select-user v-model:value="formData.liablePerson" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="验收人" v-bind="validateInfos.checkAcceptPerson">
			      <j-select-user v-model:value="formData.checkAcceptPerson" :disabled="argument.checkAcceptFlag" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="图片" v-bind="validateInfos.img">
	          <j-image-upload  v-model:value="formData.img" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="验收时间" v-bind="validateInfos.checkAcceptTime">
		        <a-date-picker placeholder="请选择验收时间"  v-model:value="formData.checkAcceptTime" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  :disabled="argument.checkAcceptFlag"/>
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="24">
          <a-form-item label="验收情况" v-bind="validateInfos.checkAcceptComment">
	          <a-textarea v-model:value="formData.checkAcceptComment" :rows="4" placeholder="请输入验收情况" :disabled="argument.checkAcceptFlag"/>
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="12">
          <a-form-item label="删除状态" v-bind="validateInfos.deleted">
            <j-dict-select-tag type='radio' v-model:value="formData.deleted" dictCode="yn" placeholder="请选择删除状态" disabled="true"/>
          </a-form-item>
        </a-col> -->
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="隐患治理过程信息" key="tbBaseDangerInvestigationReocrd" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="tbBaseDangerInvestigationReocrdTableRef"
          :loading="tbBaseDangerInvestigationReocrdTable.loading"
          :columns="tbBaseDangerInvestigationReocrdTable.columns"
          :dataSource="tbBaseDangerInvestigationReocrdTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryTbBaseDangerInvestigationReocrdListByMainId, queryDataById, saveOrUpdate } from '../TbBaseDangerInvestigation.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {tbBaseDangerInvestigationReocrdColumns} from '../TbBaseDangerInvestigation.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { Form } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { useUserStore } from '/@/store/modules/user';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "TbBaseDangerInvestigationForm",
    components:{
      JDictSelectTag,
      JSearchSelect,
      JSelectUser,
      JImageUpload,
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const tbBaseDangerInvestigationReocrdTableRef = ref();
      const tbBaseDangerInvestigationReocrdTable = reactive<Record<string, any>>({
        loading: false,
        columns: tbBaseDangerInvestigationReocrdColumns,
        dataSource: []
      });
      const activeKey = ref('tbBaseDangerInvestigationReocrd');
      const formData = reactive<Record<string, any>>({
        id: '',
        dangerLevel: '',   
        dangerSrc: '',   
        dangerManageType: '',   
        riskDeviceId: '',   
        riskUnitId: '',   
        dangerName: '',   
        dangerDesc: '',   
        dangerReason: '',   
        cost: undefined,
        dangerManageDeadline: '',   
        dangerState: '',   
        hazardDangerType: '',   
        registrant: '',   
        controlMeasures: '',   
        riskMeasureId: '',   
        registTime: dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss'),   
        liablePerson: '',   
        checkAcceptPerson: '',   
        checkAcceptComment: '',   
        checkAcceptTime: '',   
        img: '',   
        deleted: '',   
      });

      //表单验证
      const validatorRules = reactive({
        dangerLevel: [{ required: true, message: '请输入隐患等级!'},],
        dangerSrc: [{ required: true, message: '请输入隐患来源!'},],
        dangerManageType: [{ required: true, message: '请输入隐患治理类型!'},],
        riskDeviceId: [{ required: true, message: '请输入所属装置!'},],
        riskUnitId: [{ required: true, message: '请输入所属单元!'},],
        dangerName: [{ required: true, message: '请输入隐患名称!'},],
        dangerDesc: [{ required: true, message: '请输入隐患描述!'},],
        hazardDangerType: [{ required: true, message: '请输入隐患类型!'},],
        img: [{ required: true, message: '请上传图片!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });
      const argument = reactive({
        unitDictCode: "tb_base_risk_unit,risk_unit_name,id",
        checkAcceptFlag: false,
        riskUnitFlag: true
      })
      const userStore = useUserStore();

      function add() {
        resetFields();
        formData.registrant = userStore.getUserInfo.username
        tbBaseDangerInvestigationReocrdTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const tbBaseDangerInvestigationReocrdDataList = await queryTbBaseDangerInvestigationReocrdListByMainId(row['id']);
        tbBaseDangerInvestigationReocrdTable.dataSource = [...tbBaseDangerInvestigationReocrdDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'tbBaseDangerInvestigationReocrd': tbBaseDangerInvestigationReocrdTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      function changeDeviceId(id) {
        if(id){
          formData.riskUnitId = null;
          argument.riskUnitFlag = false;
        }else{
          argument.riskUnitFlag = true;
        }
        argument.unitDictCode = "tb_base_risk_unit,risk_unit_name,id,device_id="+id
      }
      
      function changeDangerManageType(value){
        if(value === '0'){
          formData.liablePerson = userStore.getUserInfo.username
          formData.checkAcceptPerson = userStore.getUserInfo.username
          formData.checkAcceptTime = dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss');
          argument.checkAcceptFlag = true;
        }else if(value === '1'){
          formData.liablePerson = null
          formData.checkAcceptPerson = null
          formData.checkAcceptTime  = null
          argument.checkAcceptFlag = false;
        }
      }


      return {
        tbBaseDangerInvestigationReocrdTableRef,
        tbBaseDangerInvestigationReocrdTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,

        argument,
        changeDeviceId,
        changeDangerManageType
      }
    }
  });
</script>